import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Modal, Select, message, Input, Row, Col } from 'antd';
import { formatMessage } from 'umi/locale';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const PropFunctionEditModal = Form.create()(props => {
  const { detail, dataTypes, units, form } = props;
  const renderOption = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));
  return (
    <Fragment>
      <FormItem style={{ marginTop: 0, marginBottom: 0 }}>
        {form.getFieldDecorator('id', { initialValue: detail.id })(<Input type="hidden" />)}
      </FormItem>
      <FormItem style={{ marginTop: 0, marginBottom: 0 }}>
        {form.getFieldDecorator('modelId', { initialValue: detail.modelId })(
          <Input type="hidden" />,
        )}
      </FormItem>
      <FormItem style={{ marginTop: 0, marginBottom: 0 }}>
        {form.getFieldDecorator('productId', { initialValue: detail.productId })(
          <Input type="hidden" />,
        )}
      </FormItem>
      <FormItem label={formatMessage({ id: 'app.dm.product.property.info.name' })} colon={false}>
        {form.getFieldDecorator('name', {
          initialValue: detail.name ? detail.name : undefined,
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'app.dm.product.property.info.name.place' }),
            },
          ],
        })(
          <Input placeholder={formatMessage({ id: 'app.dm.product.property.info.name.place' })} />,
        )}
      </FormItem>

      <FormItem label={formatMessage({ id: 'app.dm.product.property.info.label' })} colon={false}>
        {form.getFieldDecorator('label', {
          initialValue: detail.label ? detail.label : undefined,
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'app.dm.product.property.info.label.place' }),
            },
          ],
        })(
          <Input placeholder={formatMessage({ id: 'app.dm.product.property.info.label.place' })} />,
        )}
      </FormItem>

      <FormItem
        label={formatMessage({ id: 'app.dm.product.property.info.datatype' })}
        colon={false}
      >
        {form.getFieldDecorator('dataTypeId', {
          initialValue: detail.dataTypeId ? detail.dataTypeId : undefined,
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'app.dm.product.property.info.dataType.place' }),
            },
          ],
        })(
          <Select
            allowClear
            style={{ width: '100%' }}
            placeholder={formatMessage({
              id: 'app.dm.product.property.info.dataType.place',
            })}
          >
            {renderOption(dataTypes)}
          </Select>,
        )}
      </FormItem>

      <FormItem label={formatMessage({ id: 'app.dm.product.property.info.range' })} colon={false}>
        <Row style={{ width: '100%' }}>
          <Col span={10}>
            {form.getFieldDecorator('minRange', {
              initialValue: detail.range ? detail.range.split('~')[0] : undefined,
            })(
              <Input
                placeholder={formatMessage({
                  id: 'app.dm.product.property.info.minrange.place',
                })}
              />,
            )}
          </Col>
          <Col span={2} style={{ textAlign: 'center' }}>
            <span>~</span>
          </Col>
          <Col span={10}>
            {form.getFieldDecorator('maxRange', {
              initialValue: detail.range ? detail.range.split('~')[1] : undefined,
            })(
              <Input
                placeholder={formatMessage({
                  id: 'app.dm.product.property.info.maxrange.place',
                })}
              />,
            )}
          </Col>
        </Row>
      </FormItem>
      <FormItem label={formatMessage({ id: 'app.dm.product.property.info.unit' })} colon={false}>
        {form.getFieldDecorator('unitId', {
          initialValue: detail.unitId ? detail.unitId : undefined,
        })(
          <Select
            allowClear
            style={{ width: '100%' }}
            placeholder={formatMessage({ id: 'app.dm.product.property.info.unit.place' })}
          >
            {renderOption(units)}
          </Select>,
        )}
      </FormItem>
      <FormItem
        label={formatMessage({ id: 'app.dm.product.property.info.more.desc' })}
        colon={false}
      >
        {form.getFieldDecorator('desc', {
          initialValue: detail.desc ? detail.desc : undefined,
          rules: [],
        })(<TextArea rows={4} />)}
      </FormItem>
    </Fragment>
  );
});

@connect(({ product, loading }) => ({
  product,
  loading: loading.models.product,
}))
@Form.create()
class ProductFunctionEditForm extends PureComponent {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/fetchUnit',
    });
    dispatch({
      type: 'product/fetchDataType',
    });
  }

  render() {
    const {
      product: { unitList, dataTypeList, functionDetail },
      modalVisible,
      form,
      handleModalVisible,
      type,
    } = this.props;

    let typeName;
    if (type === '1') {
      typeName = formatMessage({ id: 'app.dm.product.function.table.functionType.prop' });
    } else if (type === '2') {
      typeName = formatMessage({ id: 'app.dm.product.function.table.functionType.service' });
    } else if (type === '3') {
      typeName = formatMessage({ id: 'app.dm.product.function.table.functionType.event' });
    }
    const handleEdit = (fieldsValue, mform) => {
      const { dispatch } = this.props;
      if (type === '1') {
        if (
          fieldsValue.minRange !== undefined &&
          fieldsValue.minRange !== null &&
          fieldsValue.minRange !== ''
        ) {
          if (
            fieldsValue.maxRange === undefined ||
            fieldsValue.maxRange === null ||
            fieldsValue.maxRange === ''
          ) {
            message.error({
              content: formatMessage({ id: 'app.dm.product.property.info.maxrange.place' }),
              key: 1,
            });
            return;
          }
          if (fieldsValue.maxRange <= fieldsValue.minRange) {
            message.error({
              content: formatMessage({
                id: 'app.dm.product.property.info.maxrange.must.greater.than.minrange',
              }),
              key: 1,
            });
            return;
          }
        }
        if (
          fieldsValue.maxRange !== undefined &&
          fieldsValue.maxRange !== null &&
          fieldsValue.maxRange !== ''
        ) {
          if (
            fieldsValue.minRange === undefined ||
            fieldsValue.minRange === null ||
            fieldsValue.minRange === ''
          ) {
            message.error({
              content: formatMessage({ id: 'app.dm.product.property.info.minrange.place' }),
              key: 1,
            });
            return;
          }
          if (fieldsValue.maxRange <= fieldsValue.minRange) {
            message.error({
              content: formatMessage({
                id: 'app.dm.product.property.info.maxrange.must.greater.than.minrange',
              }),
              key: 1,
            });
            return;
          }
        }

        fieldsValue.range =
          fieldsValue.minRange !== undefined &&
          fieldsValue.minRange !== null &&
          fieldsValue.minRange !== '' &&
          fieldsValue.maxRange !== undefined &&
          fieldsValue.maxRange !== null &&
          fieldsValue.maxRange !== ''
            ? `${fieldsValue.minRange}~${fieldsValue.maxRange}`
            : undefined;

        dispatch({
          type: 'product/editProp',
          payload: {
            id: fieldsValue.id,
            modelId: fieldsValue.modelId,
            productId: fieldsValue.productId,
            name: fieldsValue.name,
            label: fieldsValue.label,
            dataTypeId: fieldsValue.dataTypeId,
            unitId: fieldsValue.unitId,
            range: fieldsValue.range,
            desc: fieldsValue.desc,
          },
          mform,
          handleModalVisible,
        });
      }
    };
    const propFunctionEditProps = {
      dataTypes: dataTypeList,
      units: unitList,
      detail: functionDetail,
      form,
    };

    const okHandle = () => {
      form.validateFields((error, fieldsValue) => {
        if (error) return;
        handleEdit(fieldsValue, form);
      });
    };
    return (
      <Modal
        title={formatMessage({ id: 'app.dm.product.function.edit' })}
        destroyOnClose
        visible={modalVisible}
        width={618}
        onCancel={() => handleModalVisible()}
        onOk={okHandle}
      >
        <div style={{ width: 530, paddingLeft: 44 }}>
          <FormItem
            label={formatMessage({ id: 'app.dm.product.function.add.functionType' })}
            colon={false}
          >
            {form.getFieldDecorator('fun', {
              initialValue: typeName,
            })(<Input disabled />)}
          </FormItem>
          {type === '1' ? <PropFunctionEditModal {...propFunctionEditProps} /> : {}}
        </div>
      </Modal>
    );
  }
}
export default ProductFunctionEditForm;
